<template>
  <div class="documents">
    <div class="page-header">
      <h2>我的文档</h2>
      <el-button type="primary" @click="handleUpload">
        <el-icon><Upload /></el-icon>
        上传文档
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索文档..."
        class="search-input"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select v-model="filterType" placeholder="文档类型" clearable>
        <el-option
          v-for="item in documentTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <!-- 文档列表 -->
    <el-table
      :data="filteredDocuments"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="name" label="文档名称" min-width="200">
        <template #default="{ row }">
          <div class="document-name">
            <el-icon :size="20" :color="getDocumentIconColor(row.type)">
              <component :is="getDocumentIcon(row.type)" />
            </el-icon>
            <span>{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="120" />
      <el-table-column prop="size" label="大小" width="120" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" link @click="handlePreview(row)">
              预览
            </el-button>
            <el-button type="primary" link @click="handleDownload(row)">
              下载
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文档"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        action="/api/documents/upload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 PDF、Word、Excel 等格式文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { 
  Upload,
  Search,
  Document,
  Picture,
  VideoPlay,
  Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 状态
const loading = ref(false)
const searchQuery = ref('')
const filterType = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const uploadDialogVisible = ref(false)

// 文档类型选项
const documentTypes = [
  { label: 'PDF文档', value: 'pdf' },
  { label: 'Word文档', value: 'doc' },
  { label: 'Excel表格', value: 'xls' },
  { label: '图片文件', value: 'image' },
  { label: '视频文件', value: 'video' }
]

// 模拟文档数据
const documents = ref([
  {
    id: 1,
    name: '项目计划书.pdf',
    type: 'pdf',
    size: '2.5MB',
    updateTime: '2024-02-20 10:00:00'
  },
  {
    id: 2,
    name: '会议记录.docx',
    type: 'doc',
    size: '1.2MB',
    updateTime: '2024-02-19 15:30:00'
  },
  {
    id: 3,
    name: '财务报表.xlsx',
    type: 'xls',
    size: '3.8MB',
    updateTime: '2024-02-18 09:15:00'
  }
])

// 过滤后的文档列表
const filteredDocuments = computed(() => {
  return documents.value.filter(doc => {
    const matchesSearch = doc.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesType = !filterType.value || doc.type === filterType.value
    return matchesSearch && matchesType
  })
})

// 获取文档图标
const getDocumentIcon = (type) => {
  const icons = {
    pdf: Document,
    doc: Document,
    xls: Document,
    image: Picture,
    video: VideoPlay
  }
  return icons[type] || Document
}

// 获取文档图标颜色
const getDocumentIconColor = (type) => {
  const colors = {
    pdf: '#F56C6C',
    doc: '#409EFF',
    xls: '#67C23A',
    image: '#E6A23C',
    video: '#909399'
  }
  return colors[type] || '#909399'
}

// 处理上传
const handleUpload = () => {
  uploadDialogVisible.value = true
}

// 上传前检查
const beforeUpload = (file) => {
  const isValidType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'image/jpeg', 'image/png', 'video/mp4'].includes(file.type)
  if (!isValidType) {
    ElMessage.error('不支持的文件类型！')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess = (response) => {
  ElMessage.success('上传成功')
  uploadDialogVisible.value = false
  fetchDocuments()
}

// 上传失败
const handleUploadError = () => {
  ElMessage.error('上传失败')
}

// 预览文档
const handlePreview = (row) => {
  window.open(`/api/documents/preview/${row.id}`, '_blank')
}

// 下载文档
const handleDownload = (row) => {
  window.location.href = `/api/documents/download/${row.id}`
}

// 删除文档
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这个文档吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await axios.delete(`/api/documents/${row.id}`)
      ElMessage.success('删除成功')
      fetchDocuments()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchDocuments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDocuments()
}

// 获取文档列表
const fetchDocuments = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/documents', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        type: filterType.value,
        search: searchQuery.value
      }
    })
    documents.value = response.data.items
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchDocuments()
})
</script>

<style scoped>
.documents {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.filter-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.document-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-demo {
  width: 100%;
}
</style> 